<?php
// +----------------------------
// | Created by PhpStorm
// +----------------------------
// | Author: YnnSon
// +----------------------------
namespace app\api\model;
use app\api\service\Token;
use app\lib\enum\PageEnum;
use app\api\model\Coupon;

/**
 * 优惠券领取记录
 * Class CouponLog
 * @package app\api\model
 */
class CouponLog extends BaseModel
{

    // 关闭自动写入时间戳
    protected $autoWriteTimestamp = true;
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    protected $insert = ['create_time'];
    protected $update = ['update_time'];

    /**
     * @Desc 格式化日期
     *
     * @param $value
     *
     * @return false|string
     */
    protected function getCreateTimeAttr($value)
    {
        return date('Y-m-d', $value);
    }


    /**
     * @Desc 新增领取记录
     *
     * @param array $couponLogData 数据
     *
     * @return array
     */
    public static function insertCouponLog(array $couponLogData)
    {
        $CouponLogDb = new CouponLog();
        $CouponDb = new Coupon();

        $CouponLogDb->coupon_id = $couponLogData['coupon_id'];
        $CouponLogDb->user_weixin_id = $couponLogData['user_weixin_id'];
        $CouponLogDb->use_start_time = $couponLogData['use_start_time'];
        $CouponLogDb->use_end_time = $couponLogData['use_end_time'];
        if($CouponLogDb->isUpdate(false)->save()){
            $res = $CouponDb->where('id', $couponLogData['coupon_id'])->setInc('take_count');
            if(!$res){
                return false;
            }
        }
        return true;
    }


    public function coupon()
    {
        // log BELONGS TO 优惠券
        return $this->belongsTo('Coupon');
    }

}